package cn.walls1717.wallsmall.coupon.service.impl;

import cn.walls1717.wallsmall.common.utils.PageUtils;
import cn.walls1717.wallsmall.common.utils.Query;
import cn.walls1717.wallsmall.coupon.dao.SeckillSessionDao;
import cn.walls1717.wallsmall.coupon.entity.SeckillSessionEntity;
import cn.walls1717.wallsmall.coupon.entity.SeckillSkuRelationEntity;
import cn.walls1717.wallsmall.coupon.service.SeckillSessionService;
import cn.walls1717.wallsmall.coupon.service.SeckillSkuRelationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity>
    implements SeckillSessionService {
    @Resource
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page =
            this.page(new Query<SeckillSessionEntity>().getPage(params), new QueryWrapper<>());

        return new PageUtils(page);
    }

    /**
     * 查询最近三天的所有秒杀场次<br>
     * 今天，明天，后天。
     *
     * @return 最近三天的秒杀场次
     */
    @Override
    public List<SeckillSessionEntity> listLatest3DaysSession() {
        // 获取当前时间 2022-11-25
        LocalDate now = LocalDate.now();
        // 获取当前时间两天后 2022-11-27
        LocalDate twoDaysAfter = LocalDate.now().plusDays(2);
        // 开始时间 2022-11-25 00:00:00
        String startTime =
            LocalDateTime.of(now, LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 结束时间 2022-11-27 23:59:59
        String endTime =
            LocalDateTime.of(twoDaysAfter, LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        List<SeckillSessionEntity> sessions =
            lambdaQuery().between(SeckillSessionEntity::getStartTime, startTime, endTime).list();
        // 若当前时间区间没有秒杀场次，直接返回空。
        if (sessions == null || sessions.size() == 0) {
            return null;
        }

        // 封装秒杀场次与秒杀商品关系数据返回
        return sessions.stream().peek(session -> {
            List<SeckillSkuRelationEntity> seckillSkuRelations =
                seckillSkuRelationService.listByPromotionSessionId(session.getId());
            session.setRelationSkus(seckillSkuRelations);
        }).collect(Collectors.toList());
    }

}